package com.heng.apphook.utils

import android.content.Context
import android.util.Log
import com.heng.mapbundle2.MyLocation

/**
 * 位置信息偏好设置工具类
 * 用于保存和获取位置信息
 */
class LocationPreferences {
    companion object {
        private const val TAG = "LocationPreferences"
        private const val PREFERENCES_NAME = "location_prefs"
        private const val LATITUDE_KEY = "latitude"
        private const val LONGITUDE_KEY = "longitude"
        private const val MOCK_SWITCH_KEY = "mock_switch"
        
        /**
         * 保存位置信息
         */
        fun saveLocation(context: Context, latitude: Double, longitude: Double, isMockEnabled: Boolean) {
            val prefs = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
            prefs.edit().apply {
                putString(LATITUDE_KEY, latitude.toString())
                putString(LONGITUDE_KEY, longitude.toString())
                putBoolean(MOCK_SWITCH_KEY, isMockEnabled)
                apply()
            }
            Log.d(TAG, "Saved location: lat=$latitude, lng=$longitude, mockEnabled=$isMockEnabled")
        }
        
        /**
         * 获取保存的位置信息
         */
        fun getSavedLocation(context: Context): MyLocation? {
            val prefs = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
            val latitudeStr = prefs.getString(LATITUDE_KEY, null)
            val longitudeStr = prefs.getString(LONGITUDE_KEY, null)
            
            if (latitudeStr != null && longitudeStr != null) {
                try {
                    val latitude = latitudeStr.toDouble()
                    val longitude = longitudeStr.toDouble()
                    
                    val location = MyLocation()
                    location.latitude = latitude
                    location.longitude = longitude
                    
                    return location
                } catch (e: NumberFormatException) {
                    Log.e(TAG, "Error parsing saved location: ${e.message}")
                }
            }
            
            return null
        }
        
        /**
         * 检查是否启用了模拟位置
         */
        fun isMockEnabled(context: Context): Boolean {
            val prefs = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
            return prefs.getBoolean(MOCK_SWITCH_KEY, false)
        }
        
        /**
         * 设置模拟位置开关状态
         */
        fun setMockEnabled(context: Context, enabled: Boolean) {
            val prefs = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
            prefs.edit().putBoolean(MOCK_SWITCH_KEY, enabled).apply()
            Log.d(TAG, "Mock location ${if (enabled) "enabled" else "disabled"}")
        }
    }
}